/*
 * SaveAndLoadGame.java
 * 保存和调用游戏
 * Created on 2007年10月19日, 下午7:41
 * 本代码所有权归作者所有 如作者未声明以某项许可开放源代码
 * 则任何人不得以任何形式传播本代码
 *
 *
 */

package cn.tearcry.jsudoku;
import java.io.*;
import javax.swing.*;
import java.util.*;
import javax.swing.filechooser.FileNameExtensionFilter;
/**
 *
 * @author 马建乐
 */
public class SaveAndLoadGame {
    private int[][] puzzle;
    private int[] filledData;
    private int[] unFilledData;
    private JFrame parentFrame;
    private Map userFilledMap;
    private int wrongMoveCount;
    private int hintCount;
    /** 创建一个 SaveAndLoadGame 的新对象
     *  @param int[] 题目
     *  @param int[] 已经填写的数据
     *  @param int[] 待填写的数据
     */
    
    public SaveAndLoadGame(JFrame frame,int[][] data,Map map,int wCount,int hCount) {
        puzzle=data;
        parentFrame=frame;
        userFilledMap=map;
        wrongMoveCount=wCount;
        hintCount=hCount;
    }
    
    
    public SaveAndLoadGame() {
        
    }
    
    public boolean saveGame() {
        if(puzzle==null)
            return false;
        
        JFileChooser fileChooser=new MyFileChooser();
        fileChooser.setMultiSelectionEnabled(false);
        fileChooser.setAcceptAllFileFilterUsed(false);
        fileChooser.setFileFilter(new GameFileFilter("jsu","jSudoku游戏文件 (*.jsu)"));
        
        int choice=fileChooser.showSaveDialog(parentFrame);
        if(choice==JFileChooser.CANCEL_OPTION)
            return false;
        String fileName=fileChooser.getSelectedFile().getAbsolutePath();
        fileName=fileName.replaceAll(".jsu","");
        File file=new File(fileName+".jsu");
        try {
        PrintWriter out=new PrintWriter(new BufferedWriter(new FileWriter(file)));
            out.println("*-----------*");            
          for(int i=0;i<puzzle.length;i++) {
                out.print("|");
            for(int j=0;j<puzzle[i].length;j++) {
                if(puzzle[i][j]!=0)
                    out.print(puzzle[i][j]);
                else
                    out.print(".");
                if((j+1)%3==0)
                    out.print("|");
                    
            }
                out.println();
                if((i+1)%3==0&&i!=8)
                    out.println("|---+---+---|");
          }
            out.println("*-----------*");
            out.println("W:"+wrongMoveCount);
            out.println("H:"+hintCount);  
            Iterator iter=userFilledMap.entrySet().iterator();
            
                while(iter.hasNext()) {
                Map.Entry entry=(Map.Entry)iter.next();
                int location=((Integer)(entry.getKey())).intValue();
                int num=((Integer)entry.getValue()).intValue();
                out.println(Integer.toString(location)+":"+Integer.toString(num));
                
            }
          out.close();
        }catch(IOException ex) {
            JOptionPane.showMessageDialog(parentFrame,"游戏保存失败，请再试一次","jSudoku 保存游戏",JOptionPane.WARNING_MESSAGE);
            return false;
        }       
        return true;
    }
    
    private boolean isVaildString(String str) {
        for(int i=0;i<str.length();i++)
            if(str.charAt(i)>'9'||str.charAt(i)<'0')
                return false;
        return true;
    }
    
     private Object[] loadGame(File file) {
        String str=new String();
        HashMap map=new HashMap();
        int wrongMoveCount=0;
        int hintCount=0;
        int[][] puzzleData=new int[9][9];
        Object[] gameData=new Object[4];
        int lineNum=0,row=0,index=0;
        try{
            BufferedReader in=new BufferedReader(new FileReader(file));
                while((str=in.readLine())!=null) {
                    lineNum++;
                    
                    if(lineNum<=12&&lineNum!=1&&lineNum!=5&&lineNum!=9) {
                        str=str.replace("|","");
                        str=str.replace(".","0");
                        //输入格式不合法
                        if(!isVaildString(str))
                            throw new IOException();
                        for(int i=0;i<puzzleData[row].length;i++)
                            puzzleData[row][i]=str.charAt(i)-'0';
                            row++;
                    }
                    
                    if(lineNum==14) {
                        index=str.indexOf(":");
                        wrongMoveCount=Integer.valueOf(str.substring(index+1,str.length()));
                    }
                    if(lineNum==15) {
                        index=str.indexOf(":");
                        hintCount=Integer.valueOf(str.substring(index+1,str.length()));
                    }
                    
                    if(lineNum>=16) {
                        index=str.indexOf(":");
                        map.put(Integer.valueOf(str.substring(0,index)),
                                Integer.valueOf(str.substring(index+1,str.length())));
                    }
                        
            }
            if(lineNum==0||lineNum<=12)
               throw new IOException();
            in.close();
        }catch(IOException ex) {
            JOptionPane.showMessageDialog(parentFrame,"游戏读取失败，请再试一次","jSudoku 读取游戏",JOptionPane.WARNING_MESSAGE);
        }
        gameData[0]=puzzleData;
        gameData[1]=map;
        gameData[2]=wrongMoveCount;
        gameData[3]=hintCount;
        return gameData;
   }
     
     public Object[] loadGame() {
             JFileChooser fileChooser=new MyFileChooser();
            fileChooser.setMultiSelectionEnabled(false);
            fileChooser.setFileFilter(new GameFileFilter("jsu","jSudoku游戏文件 (*.jsu)"));
            int choice=fileChooser.showOpenDialog(parentFrame);
            if(choice==JFileChooser.CANCEL_OPTION)
                return null;
            File file=fileChooser.getSelectedFile();
            //File file=new File(fileChooser.getSelectedFile().getPath().replaceAll(".jsu","")+".jsu");
            return loadGame(file);
        }
        
    
    static class MyFileChooser extends JFileChooser {
         public MyFileChooser() {
             super();
         }
         
         public MyFileChooser(String baseDir) {
            super(baseDir);
        }

        public void approveSelection() {
            if(!validateFile(this.getSelectedFile())) {
                 JOptionPane.showMessageDialog(null,"文件不存在","jSudoku 保存游戏",JOptionPane.WARNING_MESSAGE);
                return;
            }
            super.approveSelection();
        }
        
        private boolean validateFile(File file){
                //do your validation here
                if(file.exists()&&getDialogType()==JFileChooser.SAVE_DIALOG){
                    if (JOptionPane.showConfirmDialog(null,"文件已存在，是否覆盖","jSudoku 保存游戏",
                            JOptionPane.YES_NO_OPTION) ==JOptionPane.YES_OPTION)
                        return true;
                else
                    return false;
                }
                else 
                    return true;
        }
    }
        
}



